var RiseVision = RiseVision || {};
RiseVision.Common = {};
RiseVision.Common.Sports = {};

RiseVision.Common.Sports = function(displayID) {
    var self = this;
    
    if (displayID) {
	this.displayID = displayID;
    }
    else {	//Use dummy ID.
	this.displayID = "xxx";
    }
    
    this.sport = prefs.getString("sport");
    this.collegeGames = prefs.getString("collegeGames");
    this.allSportsIndex = 0;
    this.updateInterval = 60000;
    this.allSports = ["NFL", "MLB", "NBA", "NHL", "CFOOT", "CBASK"];
}
RiseVision.Common.Sports.prototype.getData = function() {
    var self = this;
    
    this.wasReset = false;
    
    if (this.sport == "ALL") {
	this.processData("http://contentsports.appspot.com/sports/" + this.allSports[this.allSportsIndex] + ".aspx?View=Scoreboard&LogoStyle=Default" + this.getGroup() + "&DisplayId=" + this.displayId, function() {
	    self.onSportLoaded();
	});
    }
    else {
	var group = "";
	
	if ((this.sport == "CFOOT") || (this.sport == "CBASK")) {
	    group = "&Group=" + this.collegeGames;
	}
	
	this.processData("http://contentsports.appspot.com/sports/" + this.sport + ".aspx?View=Scoreboard&LogoStyle=Default" + group + "&DisplayId=" + this.displayID, function() {
	    self.getLogoURLs();   
	});
    }
}
RiseVision.Common.Sports.prototype.processData = function(url, callback) {
    var	self = this,
	params = {};
	
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 60;
    gadgets.io.makeRequest(url, function(obj) {
	if (obj.data) {
	    var data = obj.data,
		game = data.getElementsByTagName("Game"),
		sportCode = "", sportName, i;
		
	    if (!self.wasReset) {
		self.sports = [];
		self.games = [];
		self.logoCount = 0;
		self.totalLogos = 0;
		self.wasReset = true;
	    }
	    
	    if (data) {
		if (data.getElementsByTagName("Sport").length > 0) {
		    sportCode = data.getElementsByTagName("Sport")[0].getAttribute("Code");
		}
		
		if (game.length > 0) {
		    sportName = self.getNodeValue(data.getElementsByTagName("Title"));
    
		    self.totalLogos++;
		    self.sports.push({
			sportCode: sportCode,
			name: sportName
		    });
		}
		
		//Get game stats.
		for (i = 0; i < game.length; i++) {
		    var status = "",
			extendedStatus = "",
			team = game[i].getElementsByTagName("Team"),
			overUnder = "",
			host, visitor, home, j, date;
			
			if (game[i].getElementsByTagName("Status").length > 0) {
			    status = game[i].getElementsByTagName("Status")[0].getAttribute("Code");
			}
			
			extendedStatus = self.getNodeValue(game[i].getElementsByTagName("Extended"));
	
			if (game[i].getElementsByTagName("Over_Under").length > 0) {
			    if (game[i].getElementsByTagName("Over_Under")[0].getElementsByTagName("Casino").length > 0) {
				overUnder = "O/U " + game[i].getElementsByTagName("Over_Under")[0].getElementsByTagName("Casino")[0].getAttribute("value");
			    }
			}
			
			date = self.getNodeValue(game[i].getElementsByTagName("Date"));
			
			if (date) {
			    date = Date.parse(date);
			}
			
			for (j = 0; j < team.length; j++) {
			    host = team[j].getAttribute("Host");
			    
			    if (host == "Visiting") {
				visitor = self.getTeamInfo(team[j], sportCode);
			    }
			    else if (host == "Home") {
				home = self.getTeamInfo(team[j], sportCode);
			    }		    
			}
		    
		    self.games.push({
			sportCode: sportCode,
			date: date,
			status: status,
			extendedStatus: extendedStatus,
			overUnder: overUnder,
			visitor: visitor,
			home: home
		    });
		}
		
		callback();
	    }
	    else {
		console.log("Invalid data source URL");
	    }
	}
	else {
	    setTimeout(function() {
		$(self).trigger("updateTimerExpired");
	    }, self.updateInterval);
	}
    }, params);
}
RiseVision.Common.Sports.prototype.onSportLoaded = function() {
    var self = this, group;
    
    this.allSportsIndex++;
    
    group = this.getGroup();
    
    if (this.allSportsIndex == this.allSports.length) {	//All games for all sports have been loaded.
	this.allSportsIndex = 0;
	this.getLogoURLs();
    }
    else {	//Load games for next sport.
	this.processData("http://contentsports.appspot.com/sports/" + this.allSports[this.allSportsIndex] + ".aspx?View=Scoreboard&LogoStyle=Default" + group + "&DisplayId=" + this.displayID, function() {
	    self.onSportLoaded();
	});
    }
}
RiseVision.Common.Sports.prototype.getGroup = function() {
    var group = "";
    
    if ((this.allSports[this.allSportsIndex] == "CFOOT") || (this.allSports[this.allSportsIndex] == "CBASK")) {
	group = "&Group=" + this.collegeGames;
    }

    return group;
}
RiseVision.Common.Sports.prototype.getTeamInfo = function(team, sportCode) {
    var spread = "",
	img = new Image();
    
    if (team.getElementsByTagName("Casino").length > 0) {
	spread = team.getElementsByTagName("Casino")[0].getAttribute("value");
    }
    
    this.totalLogos++;
    
    return {
	name: this.getNodeValue(team.getElementsByTagName("Name")),
	rank: this.getNodeValue(team.getElementsByTagName("Rank")),
	overall: this.getNodeValue(team.getElementsByTagName("Overall")),
	score: this.getNodeValue(team.getElementsByTagName("Total")),
	spread: spread
    };
}
RiseVision.Common.Sports.prototype.getNodeValue = function(node) {
    if (node.length > 0) {
	if (node[0].childNodes.length > 0) {
	    return node[0].childNodes[0].nodeValue;
	}
	else {
	    return "";
	}
    }
    
    return "";
}
RiseVision.Common.Sports.prototype.getLogoURLs = function() {
    var filter = "", self = this;
    
    if (this.sports.length > 0) {
	$.each(this.sports, function(index, value) {
	    if (filter == "") {
		filter = " where upper(A) = '" + value.sportCode + "'";
	    }
	    else {
		filter += " or upper(A) = '" + value.sportCode + "'";
	    }
	});
	
	var settings = {
	    url: "https://docs.google.com/a/risevision.com/spreadsheet/tq?key=0AnsiFJce3EYCdHA5NWp2VVVxV1pZUFFHMmpiUGx1TXc&gid=1&headers=1",
	    refreshInterval: 0,
	    queryString: "select A, B, C" + filter,
	    callback: function(data) {
		var len = data.getNumberOfRows();
		    
		for (var row = 0; row < len; row++) {
		    if ($.trim(data.getValue(row, 1).toLowerCase()) == "sport") {
			//Match logo to proper sport.
			$.each(self.sports, function(index, value) {
			    if ($.trim(value.sportCode.toLowerCase()) == $.trim(data.getValue(row, 0).toLowerCase())) {
				value.logo = data.getValue(row, 2);
				return false;
			    }
			});
		    }
		    else {
			//Match logo to proper team.
			$.each(self.games, function(index, value) {
			    if ($.trim(value.sportCode.toLowerCase()) == $.trim(data.getValue(row, 0).toLowerCase())) {
				if ($.trim(value.visitor.name.toLowerCase()) == $.trim(data.getValue(row, 1).toLowerCase())) {
				    value.visitor.logo = data.getValue(row, 2);
				    //return false;	Issue 591 - Same team may appear in games more than once.
				}
				
				if ($.trim(value.home.name.toLowerCase()) == $.trim(data.getValue(row, 1).toLowerCase())) {
				    value.home.logo = data.getValue(row, 2);
				    //return false;	Issue 591 - Same team may appear in games more than once.
				}
			    }
			});
		    }
		}
		
		self.loadLogos();
	    }
	};
	
	getFilteredData(settings);
    }
    else {
	$(this).trigger("noData");
    }
}
RiseVision.Common.Sports.prototype.loadLogos = function() {
    var self = this;
    
    //Load all sports logos.
    $.each(this.sports, function(index, value) {
	self.loadLogo(index, value.logo, true, false);
    });    
    
    //Load all team logos.
    $.each(this.games, function(index, value) {
	self.loadLogo(index, value.visitor.logo, false, true);
    });
    
    $.each(this.games, function(index, value) {
	self.loadLogo(index, value.home.logo, false, false);
    });
}
RiseVision.Common.Sports.prototype.loadLogo = function(index, url, isSport, isVisitor) {
    var self = this,
	img = new Image();

    img.onload = function () {
	self.logoCount++;
	self.onImageLoaded.call(self);
    }
    
    img.onerror = function() {
	if (isSport) {
	    self.sports[index].logo = "";
	}
	else if (isVisitor) {
	    self.games[index].visitor.logo = "";
	}
	else {
	    self.games[index].home.logo = "";
	}
	
	self.logoCount++;
	self.onImageLoaded.call(self);
    }
    
    img.src = url;
}
RiseVision.Common.Sports.prototype.onImageLoaded = function() {
    if (this.logoCount >= this.totalLogos) {
	var self = this;
    
	setTimeout(function() {
	    $(self).trigger("updateTimerExpired");
	}, this.updateInterval);
	
	$(this).trigger("imagesLoaded");
    }
}